<?php
declare(strict_types=1);
/**
 * This file is part of EasySwoole.
 *
 * @link     https://www.easyswoole.com
 * @document https://www.easyswoole.com
 * @contact  https://www.easyswoole.com/Preface/contact.html
 * @license  https://github.com/easy-swoole/easyswoole/blob/3.x/LICENSE
 */

namespace App\Service\Captcha;

use App\Exception\Api\BadRequestException;
use App\Service\BaseService;
use App\Utility\IdUtil;
use App\Utility\Redis\RedisUtil;
use EasySwoole\Utility\Random;
use EasySwoole\VerifyCode\Conf;
use EasySwoole\VerifyCode\VerifyCode;

class CaptchaService extends BaseService
{
    public function getCaptchaImgBase64()
    {
        $config = new Conf();
        $config->setFontSize(16);
        $config->setImageWidth(111);
        $config->setImageHeight(36);
        $code         = new VerifyCode($config);
        $captchaValue = Random::character(4, '234567890AaBbCcDdEeFfGgHhJjKkMmNnPpQqRrSsTtUuVvWwXxYyZz');
        $drawCode     = $code->DrawCode($captchaValue);
        return [$captchaValue, $drawCode->getImageBase64()];
    }

    public function createCaptchaCode()
    {
        // 获取运算的结果
        [$captchaValue, $imgBase64] = $this->getCaptchaImgBase64();
        $captchaConfig = config('app.captcha');
        $uuid          = $captchaConfig['code-key'] . IdUtil::simpleUUID();

        // 保存验证码
        RedisUtil::setex($uuid, $captchaValue, $captchaConfig['expiration']);

        // 验证码信息
        return ['img' => $imgBase64, 'uuid' => $uuid];
    }

    public function checkCaptchaCode(string $uuid, string $code)
    {
        // 查询验证码
        $redisCode = RedisUtil::get($uuid);
        // 清除验证码
        RedisUtil::del($uuid);
        if (!$redisCode) {
            throw new BadRequestException("验证码不存在或已过期");
        }
        if ((string)$code !== $redisCode) {
            throw new BadRequestException("验证码错误");
        }
    }
}
